<template>
    <!-- <el-card shadow="never" style="border: none; width: 100%;"> -->
    <div class="search-container">
        <p class="textitem flex-start" style="font-size: 18px; margin-bottom: 16px;" placeholder="请输入关键字">
            机构管理
        </p>
        <el-form class="search-form" @submit.prevent style="margin: 40px 0 20px;">
            <el-row :gutter="0">
                <el-col :span="18" class="no-padding">
                    <el-form-item @submit.prevent>
                        <el-input v-model="onsearchDate.searchValue" style=" width: 376px;height: 40px;" size="large"
                            placeholder="请输入关键字" :suffix-icon="Search" @keyup.enter.prevent="onSearch" />
                    </el-form-item>
                </el-col>
                <el-col :span="6" class="flex-end">
                    <router-link to="/data/organization/add"><el-button type="primary"
                            style="margin-right: 12px;">新增机构</el-button>
                    </router-link>
                    <!-- <el-button>导出</el-button> -->
                </el-col>
            </el-row>
        </el-form>
    </div>
    <!-- 表格顶部的操作栏 -->
    <div style="margin-bottom: var(--card-space);" v-if="$slots.toolbar">
        <slot name="toolbar"></slot>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData.rows"
        :header-cell-style="{ background: '#ccddff', fontWeight: 'normal', color: '#515a6e', textAlign: 'center' }"
        style="font-size: 13px;">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" prop="_id" min-width="150" align="center">
        </el-table-column>
        <!-- <el-table-column label="编号" prop="_id">
                <template #default="scope">
                    {{ scope.row._id ? scope.row._id.substring(0, 6) : '' }}
                </template>
</el-table-column> -->



        <!-- import.meta.env.VITE_BASE_URL -->
        <el-table-column label="机构图片" align="center">
            <template #default="scope">
                <el-upload class="avatar-uploader" :action="`${baseURL}/image/upload`" :show-file-list="false"
                    name="file" :on-success="(res: any) => handleImageSuccess(res, scope.row)">
                    <img v-if="scope.row.image" :src="scope.row.image" class="avatar"
                        style="width: 55px;height: 55px;" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Picture />
                    </el-icon>
                </el-upload>
            </template>
        </el-table-column>


        <el-table-column label="机构名称" prop="name" required min-width="200" align="center" />
        <el-table-column label="负责人姓名" prop="contacts" align="center" />
        <el-table-column label="电话" align="center">
            <template #default="scope">
                {{ scope.row.phone ? scope.row.phone.slice(0, 3) + '****' + scope.row.phone.slice(7) : '' }}
            </template>
        </el-table-column>
        <el-table-column label="机构地址" prop="address" required min-width="200" align="center" />

        <el-table-column label="状态" align="center">
            <el-switch v-model="searchData.state" inline-prompt active-text="启动" inactive-text="禁止"
                style="--el-switch-on-color: #13ce66;  --el-switch-disabled-color: #ccc;" />
        </el-table-column>
        <el-table-column label="操作" align="center">
            <!-- scope.row 获取到当前这一行的数据对象 -->
            <template #default="scope">
                <!-- 点击事件：父组件调用子组件的方法，同时传值给子组件 -->
                <el-button link type="primary" @click="toUpdate(scope.row._id)">
                    修改
                </el-button>

                <el-button link style="color:#FA7468;" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <div v-if="pageData" class="flex-end" style="margin-top: 22px;">
        <el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
            :total="tableData.total ?? 0" :page-sizes="[3, 5, 10, 20]" background
            layout="total, sizes, prev, pager, next, jumper" />
    </div>

    <!-- </el-card> -->
</template>
<script setup lang="ts">

import { deleteOrganizationApi, findOrganizationsApi, OrganizationsType } from '@/api/organizationManage';
import { UploadProps } from 'element-plus';
import { Picture } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, watch } from 'vue';
const baseURL = import.meta.env.VITE_BASE_URL;
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
const tableData = reactive({
    rows: [], total: 0
})
const pageData = ref({
    currentPage: 1,
    pageSize: 5
});
const searchData = ref({ state: '' });
defineProps<{
    data: any[],
    columns: ColumnItem[],
    total?: number
}>();
const tableItem = ref<OrganizationsType>({
    _id: '', image: '', name: '', contacts: '', phone: '', address: '', intro: '', state: 1
});

// 图片上传后执行的方法
const handleImageSuccess = (res: any, row: any) => {
    if (res.code == 200) {
        row.image = res.data;
    }
}

//  查询机构管理数据的请求
onMounted(() => {
    findOrganization();
})
function findOrganization(_p0?: {
    /// <reference path="./__VLS_fake.d.ts" />
    value:
    /// <reference path="./__VLS_fake.d.ts" />
    string;
}) {
    findOrganizationsApi({
        // page: pageData.value.currentPage,
        // pageSize: pageData.value.pageSize,
        ...pageData.value,
        value: onsearchDate.value.searchValue
    })
        .then(res => {
            if (res.code == 200) {

                tableData.rows = res.data.rows;
                tableData.total = res.data.total;
            }
        })
}



//点击查询的按钮  双向绑定
const onsearchDate = ref({ searchValue: '' });
// 点击查询的点击事件   查询按钮发一次请求查询      findOrganization(params = {})里要传参--------------
function onSearch() {
    console.log("搜索的值", onsearchDate.value);
    findOrganization({
        value: onsearchDate.value.searchValue
    })
    console.log("1111", findOrganization);
}



// 点击删除事件
function handleDelete(row: OrganizationsType) {
    // 弹出确认框
    ElMessageBox.confirm(
        `机构信息删除后无法恢复，确定要删除吗？`,
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteOrganizationApi({ _id: row._id }).then(res => {
            if (res.code === 200) {
                tableData.rows = tableData.rows.filter(item => item._id !== row._id);
                ElMessage.success('删除成功');
            } else {
                ElMessage.error('删除失败');
            }
        }).catch(() => {
            ElMessage.error('删除失败，请重试');
        });
    })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}
const router = useRouter();
const toUpdate = (_id: string) => {
    router.push(`/data/organization/update/${_id}`);

}

watch(pageData, () => {

    console.log(pageData.value);

    findOrganization();
}, { deep: true });

</script>
<style scoped lang="scss">
.search-form .el-form-item {
    margin-bottom: 0 !important;
}

.no-padding {
    padding-left: 0 !important;
}

.flex-start {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.search-container {
    padding: 20px 0;
    background: #fff;
    border-radius: 4px;
}

.search-form {
    width: 100%;
}

.textitem {
    position: relative;
    padding-left: 12px;
    /* 给蓝色小条留出空间 */
}

.textitem::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 20px;
    background-color: rgba(41, 132, 248, 1);
    border-radius: 8px;
}

.avatar {
    width: 75px;
    height: 54px;
    display: block;
    /* 确保图片是块级元素 */
}

::placeholder {
    color: rgb(204, 204, 204);
}
</style>